import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { Slider } from '@/components/ui/slider'
import { Button } from '@/components/ui/button'
import { CustomDialog } from '@/components/CustomDialog'
import DeclarationForm from './DeclarationForm'
import { useVideoStore } from '@/stores/video'
import { commonService } from '@/services'
import { Toast } from '@/hooks/use-toast'
interface AudioSettingsProps {
  isCreateAudio?: boolean
  cancelClick?: () => void
  confirm: (o: {
    vol: string
    speed: string
    tone_id: string
    audioLabel: string
    url?: string
  }) => void
  defVal?: {
    vol: string
    speed: string
    tone_id: string
  }
}

const AudioSettings: React.FC<AudioSettingsProps> = ({
  cancelClick = () => {},
  confirm,
  defVal,
  isCreateAudio = false,
}) => {
  const [text, setText] = useState('')
  const [speed, setSpeed] = useState(1)
  const [vol, setVolume] = useState(1)
  const { toneList: audioList, fetchToneList } = useVideoStore()
  const [audioValue, setAudioValue] = useState('')

  useEffect(() => {
    fetchToneList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  useEffect(() => {
    if (defVal) {
      setSpeed(Number(defVal.speed) || 1)
      setVolume(Number(defVal.vol) || 1)
      setAudioValue(defVal.tone_id)
    }
  }, [defVal])

  const handleCheck = (id: string) => {
    setAudioValue(id)
  }
  const handleConfirm = () => {
    if (isCreateAudio) {
      // 音频生成
      commonService
        .getAudioList({
          text,
          voice_setting: {
            voice_id: audioList.find((item) => item.value + '' === audioValue)
              ?.voice_id!,
            speed,
            vol,
            pitch: 1, // 音调
          },
        })
        .then((url: string) => {
          console.log(url)
          Toast.show({
            content: '音频生成功！',
            icon: 'success',
          })
          cancelClick()
          confirm({
            url: url,
            vol: String(vol),
            speed: String(speed),
            tone_id: audioValue,
            audioLabel:
              audioList.find((item) => item.value + '' === audioValue)?.label ?? '',
          })
        })
        .catch((error: any) => {
          console.error(error)
          Toast.clear()
          Toast.show({
            content: error instanceof Error ? error.message : '音频生成失败',
            icon: 'error',
          })
        })
    } else {
      confirm({
        // label:
        vol: String(vol),
        speed: String(speed),
        tone_id: audioValue,
        audioLabel:
          audioList.find((item) => item.value + '' === audioValue)?.label ?? '',
      })
      cancelClick()
    }
  }

  return (
    <Card
      // className={`${isCreateAudio ? 'w-full border-none shadow-none' : 'w-full'}`}
      className="w-full border-none shadow-none bg-transparent"
    >
      <CardContent className="space-y-6 p-0 border-none">
        {isCreateAudio && (
          <div className="space-y-2">
            <label className="text-sm text-gray-500">Text Content:</label>
            <Textarea
              value={text}
              placeholder="Enter text here"
              onChange={(e) => setText(e.target.value)}
              className="w-full h-32 resize-none rounded-[10px] text-white border border-transparent focus:border-white bg-white/5 placeholder:text-white/40"
            />
          </div>
        )}
        <div className="space-y-2">
          {/* <label className="text-sm text-gray-500">声音选择:</label> */}
          <Select value={audioValue} onValueChange={setAudioValue}>
            <SelectTrigger className="w-full bg-white/5 border h-[38px] rounded-[10px] text-white/40 border-transparent data-[state=open]:border-white">
              <SelectValue placeholder="Select Sound" />
            </SelectTrigger>
            <SelectContent className="bg-[#26252E] border-none">
              {audioList?.map((item) => (
                <SelectItem key={item.id} value={item.value + ''}>
                  {item.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="w-full">
          <CustomDialog
            className="sm:max-w-[425px]"
            trigger={
              <Button
                className="w-full border-none text-[#A091FD] bg-white/5 hover:bg-white/10 rounded-[10px] h-[38px]"
                variant="outline"
              >
                Clone Sound
              </Button>
            }
            fnChildren={(handleCancel) => (
              <DeclarationForm
                onSubmit={(value) => {
                  handleCheck(value)
                  handleCancel()
                }}
                cancelClick={handleCancel}
              />
            )}
          ></CustomDialog>
        </div>
        <div className="space-y-4">
          <div className="space-y-2">
            <div className="flex justify-between">
              <label className="text-sm select-none text-gray-500">
                Speech rate ({speed}):
              </label>
            </div>
            <Slider
              value={[speed]}
              max={2}
              min={0.5}
              step={0.1}
              className="w-full"
              onValueChange={(value) => setSpeed(value[0])}
            />
          </div>

          <div className="space-y-2">
            <div className="flex justify-between">
              <label className="text-sm select-none text-gray-500">
                Volume ({vol}):
              </label>
            </div>
            <Slider
              value={[vol]}
              max={10}
              min={0}
              step={1}
              className="w-full"
              onValueChange={(value) => setVolume(value[0])}
            />
          </div>
        </div>

        <div className="flex justify-end space-x-2 pt-10 px-6">
          {/* <Button variant="outline" className="w-20" onClick={cancelClick}>
            Cancel
          </Button> */}
          <Button
            className="w-full rounded-full h-11 font-ak text-base font-medium disabled:bg-white/10 disabled:text-white/40"
            onClick={handleConfirm}
            disabled={!text || !audioValue}
          >
            Generate
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}

export default AudioSettings
